﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Security;

namespace KingSite.Purview.MVC
{
    [Authorize]
    public class PurviewController : Controller
    {
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            bool isAjax = filterContext.HttpContext.Request.IsAjaxRequest();
            if (!Authorize(filterContext))
            {
                string j = "对不起，您没有访问权限！";
                if (!isAjax)
                {
                    filterContext.HttpContext.Response.Redirect("~/403.html");
                }
                else
                {
                    filterContext.HttpContext.Response.StatusCode = 403; //没有权限访问                    
                    filterContext.RequestContext.HttpContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
                    filterContext.RequestContext.HttpContext.Response.Write(j);
                }
                filterContext.RequestContext.HttpContext.Response.End();
                throw new Exception(j);
            }
            else
            {
                base.OnActionExecuting(filterContext);
            }

        }

        //权限判断业务逻辑
        private bool Authorize(ActionExecutingContext filterContext)
        {

            var controllerName = filterContext.RouteData.Values["controller"].ToString();
            var actionName = filterContext.RouteData.Values["action"].ToString();

            MembershipExProvider _provider = (MembershipExProvider)Membership.Provider;
            if (_provider.CanDo(User.Identity.Name, controllerName, actionName))
            {
                return true;
            }
            else
            {
                return false;
            }

        }
    }
}
